﻿#include "iowidget.h"
#include <QGridLayout>
#include <QLabel>
#include <QtDebug>
IOWidget::IOWidget(QWidget *parent) : QWidget(parent)
{
    initGUI();
}

void IOWidget::initGUI()
{
    QGridLayout *pGridLayout = new QGridLayout;
    QLabel * label = new QLabel;
    label->setText(u8"IN");
    pGridLayout->addWidget(label, 0, 0, Qt::AlignHCenter);

    label = new QLabel;
    label->setText(u8"OUT");
    pGridLayout->addWidget(label, 1, 0, Qt::AlignHCenter);

    for(int i = 0; i < 8; i++)
    {
        m_pLed[i] = new QSimpleLed;
        m_pPushBotton[i] = new QPushButton;
        m_pPushBotton[i]->setText(QString("%1").arg(i + 1));
        m_pPushBotton[i]->setCheckable(true);
        connect(m_pPushBotton[i], &QPushButton::clicked, this, &IOWidget::on_pushButtonClicked);
        pGridLayout->addWidget(m_pLed[i], 0, i + 1, Qt::AlignHCenter);
        pGridLayout->addWidget(m_pPushBotton[i], 1, i + 1, Qt::AlignHCenter);
    }
    setLayout(pGridLayout);


}

void IOWidget::setINPort(int port, uint32_t value)
{
    Q_UNUSED(port);
    if( value != m_inValue )
    {
        m_inValue = value;
        for(int i = 0; i < 8 ; i++)
        {
            if(value & 0b01 << i)
            {
                m_pLed[i]->setStates(QSimpleLed::ON);
            }
            else
            {
                m_pLed[i]->setStates(QSimpleLed::OFF);
            }
        }

    }
}

void IOWidget::on_pushButtonClicked()
{
    QPushButton *p = dynamic_cast<QPushButton *>(sender());

    for(int axis = 0; axis < 8; axis++)
    {
        if(p == m_pPushBotton[axis])
        {
            qDebug() << "outPortChanged(axis, m_pPushBotton[axis]->isChecked())";
            emit outPortChanged(axis, m_pPushBotton[axis]->isChecked());
            break;
        }
    }
}
